package group.raber.base.autoconfigure;

import group.raber.base.filter.WebHolderFilter;
import group.raber.base.listener.WebHolderListener;
import group.raber.jeki.autoconfigure.beetl.template.BeetlTemplateProperties;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

//@EnableWebMvc //该注解在零配置时，有用，有手动配置时，会报错
@Configuration
@ComponentScan(basePackages={"group.raber.base"})
@ServletComponentScan
@EnableConfigurationProperties(BaseProperties.class)
//@ServletComponentScan("group.raber.base")
//public class BaseAutoConfiguration extends WebMvcConfigurerAdapter {
public class BaseAutoConfiguration {
    /**
     * 定义错误页面显示映射
     * @return
     */
    @Bean
    public EmbeddedServletContainerCustomizer getContainerCustomizer(){
        return new EmbeddedServletContainerCustomizer(){
            public void customize(ConfigurableEmbeddedServletContainer container) {
                //请求转给对应的Controller进行处理
                container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST,"/400"));
                container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404"));
                container.addErrorPages(new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED,"/405"));
                container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/500"));

            }
        };
    }

    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new WebHolderListener());
        return servletListenerRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean indexFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new WebHolderFilter());
        registration.addUrlPatterns("/");
        return registration;
    }

//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(new GlobalVariableInterceptor()).addPathPatterns("/**");
//        super.addInterceptors(registry);
//    }
//
//    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//        configurer.enable();
//    }
}
